﻿using System;
using System.ComponentModel;
using System.Net;
using Avalonia.Controls;
using DevManager.Services;

namespace DevManager.StatusBars;

public partial class DownloadBar : StatusBar
{
    private readonly DownloadModel _model;

    [Obsolete("虽然我知道WebClient已经过时了，但是现在还没办法")]
    public DownloadBar(DownloadModel model)
    {
        InitializeComponent();
        _model = model;
        DownloadBlock = this.FindControl<TextBlock>("DownloadBlock");
        DownloadBlock!.Text = $"正在下载 : {model.Name}";
        Bar = this.FindControl<ProgressBar>("Bar");
        var client = new WebClient();
        client.DownloadProgressChanged += DownloadProgressChanged;
        client.DownloadFileCompleted += ClientOnDownloadFileCompleted;

        var uri = new Uri(model.Url);
        client.DownloadFileAsync(uri, model.FilePath);
    }

    private void ClientOnDownloadFileCompleted(object? sender, AsyncCompletedEventArgs e)
    {
        if (sender is not WebClient client) return;
        client.Dispose();
        InstallService.FileInstall(_model.FilePath);
        IsVisible = false;
    }

    private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        var receive = double.Parse(e.BytesReceived.ToString());
        var total = double.Parse(e.TotalBytesToReceive.ToString());
        Bar.Value = receive / total * 100;
    }
}

public class DownloadModel
{
    public string Name { get; init; } = "";
    public string FilePath { get; init; } = "";
    public string Url { get; init; } = "";
}